<script setup>

import {useRouter} from "vue-router";
import {onMounted, reactive, ref} from "vue";
import {
    copySurveysApi,
    deleteSurveysApi,
    getSurveysApi,
    getSurveysByIdApi,
    getSurveysListApi,
    saveSurveysApi,
    updateSurveysApi
} from "../../apis/SurveysApi.js";
import {Message, Modal} from "@arco-design/web-vue";
import {getShareUrl, getSurveysStatusText} from "../../utils/CommonsUtil.js";
import {BASE_URL} from "../../config/index.js";
import {applyTemplateApi} from "../../apis/TemplateApi.js";

const router = useRouter()
const surveysList = ref([])
const uploadList = ref([])
const coverUploadList = ref([])
const page = ref(1)
const size = ref(10)
const isPreviewBg = ref(false)
const formRef = ref()
const isShowConfig = ref(false)
const isShowShare = ref(false)
const form = ref({})
const shareUrl = ref('')
//点击分享的问卷id
const shareId = ref('')
const shareName = ref('')
const dataLoading = ref(false);

const pagination = ref({
    current: page.value,
    pageSize: size.value,
    total: 0, // 总条数初始为0
    showTotal: true, // 显示总数
    showPageSize: true, // 显示页码切换器
    showJumper: true, // 显示快速跳转
});

// 修改后的获取数据方法
const getSurveys = async () => {
    dataLoading.value = true;
    const res = await getSurveysListApi(pagination.value.current, pagination.value.pageSize, {})
    if (res.code === 0) {
        surveysList.value = res.data.records
        pagination.value.total = Number(res.data.total)
    } else {
        Message.error(res.message)
    }
    dataLoading.value = false;
}

const saveConfig = async () => {
    console.log('保存配置', form.value)
    //校验
    formRef.value.validate()
    //请求
    const res = await updateSurveysApi(form.value)
    if (res.code === 0) {
        Message.success('保存成功')
        isShowConfig.value = false
        await getSurveys()
        return true
    } else {
        Message.error(res.message)
        return false
    }

};

const handleShare = (data) => {
    //获取分享链接 前端端口
    shareUrl.value = getShareUrl(data.id)
    shareId.value = data.id
    shareName.value = data.title
    isShowShare.value = true
};

const handleConfig = async (id) => {
    const res = await getSurveysByIdApi(id)
    if (res.code === 0) {
        form.value = res.data
        uploadList.value = []
        isShowConfig.value = true
    }else{
        Message.error(res.message)
    }

};
const handleData = (id) => {
    //跳转
    router.push(`/statistics/${id}`)
}
const handleCopy = (data) => {
    Modal.info({
        title: '提示',
        content:'确认复制问卷吗',
        onOk: async () => {
            const res = await copySurveysApi(data.id)
            if (res.code === 0) {
                Message.success('复制成功');
                await getSurveys(); // 刷新列表
            } else {
                Message.error(res.message);
            }
        },
    })
};

const handleEdit = (id) => {
    router.push(`/workbench/${id}`)
};
const removeUpload = (file) => {
    uploadList.value = []
    form.value.bgimg = ''
    return true
}

const handleDelete = async (id) => {
    try {
        Modal.warning({
            title: '警告',
            content: '删除后问卷数据无法还原 确认删除吗？',
            onOk: async () => {
                const res = await deleteSurveysApi(id)
                if (res.code === 0) {
                    Message.success('删除成功');
                } else {
                    Message.error(res.message);
                }
                await getSurveys(); // 刷新列表
            },
        });
    } catch (error) {
        Message.error('删除失败');
    }
};

// 处理分页变化事件
const handlePageChange = (current) => {
    pagination.value.current = current
    getSurveys()
}
const timeOk = (time) => {
    form.value.starttime = time[0]
    form.value.endtime = time[1]
};
// 处理每页数量变化事件
const handlePageSizeChange = (pageSize) => {
    pagination.value.pageSize = pageSize
    getSurveys()
}
const createSurveys = () => {
    router.push("/workbench")
}
const copyUrl = async () => {
    try {
        await navigator.clipboard.writeText(shareUrl.value);
        Message.success('复制成功');
    } catch (e) {
        Message.error('复制失败');
    }
};
const goPreview = () => {
    location.href = shareUrl.value
}
const uploadSuccess = (res) => {
    form.value.bgimg = res.response.data.url
}
const uploadCoverSuccess = (res) => {
    form.value.cover = res.response.data.url
}
const removeCoverUpload = (file) => {
    coverUploadList.value = []
    form.value.cover = ''
    return true
}

//申请上传模板
const uploadTemplate = async () => {
    if (!shareId.value) {
        Message.error('请先选择问卷')
        return
    }
    const res = await applyTemplateApi(shareId.value)
    if (res.code === 0) {
        Message.success('申请成功,请等待审核')
    } else {
        Message.error(res.message)
    }
}
onMounted(async () => {
    await getSurveys()
})

</script>

<template>

    <div class="py-8 px-24">
        <a-button type="primary" @click="createSurveys">创建问卷</a-button>
        <a-table
            :scroll="{x:2000,y:900}"
            bordered
            stripe
            :loading="dataLoading"
            :data="surveysList"
            :pagination="pagination"
            @page-change="handlePageChange"
            @page-size-change="handlePageSizeChange"
            class="mt-4 "
        >
            <template #columns>
                <!-- 问卷标题 -->
                <a-table-column
                    title="问卷标题"
                    data-index="title"
                    :width="200"
                />
                <!-- 问卷状态 -->
                <a-table-column
                    title="状态"
                    data-index="status"
                    :width="110"
                >
                    <template #cell="{ record }">
                        <a-tag color="#7bc616" v-if="record.status === 0"> {{ getSurveysStatusText(record.status)}}</a-tag>
                        <a-tag color="#165dff" v-if="record.status === 1"> {{ getSurveysStatusText(record.status)}}</a-tag>
                        <a-tag color="#ff5722" v-if="record.status === 2"> {{ getSurveysStatusText(record.status)}}</a-tag>

                    </template>
                </a-table-column>

                <a-table-column title="登录校验" data-index="isLogin" :width="120">
                    <template #cell="{ record }">
                        {{ record.isLogin === 1 ? '需要' : '不需要' }}
                    </template>
                </a-table-column>


                <a-table-column
                    :sortable="{ sortDirections: ['ascend', 'descend']}"
                    title="提交次数"
                    data-index="submitNum"
                    :width="120"
                />


                <!-- 生效时间 -->
                <a-table-column title="生效时间" data-index="starttime" :width="180">
<!--                    <template #cell="{ record }">-->
<!--                        {{ new Date(record.starttime).toLocaleString() }}-->
<!--                    </template>-->
                </a-table-column>
                <!-- 结束时间 -->
                <a-table-column title="结束时间" data-index="endtime" :width="180">
<!--                    <template #cell="{ record }">-->
<!--                        {{ new Date(record.endtime).toLocaleString() }}-->
<!--                    </template>-->
                </a-table-column>

                <!-- 创建时间 -->
                <a-table-column :sortable="{ sortDirections: ['ascend', 'descend']}" title="创建时间" data-index="createtime" :width="180">
                    <!--                    <template #cell="{ record }">-->
                    <!--                        {{ new Date(record.createtime).toLocaleString() }}-->
                    <!--                    </template>-->
                </a-table-column>
                <!-- 问卷描述 -->
                <a-table-column
                    :width="320"
                    title="问卷描述"
                    data-index="description"
                    :ellipsis="true"
                />

                <!-- 操作列 -->
                <a-table-column
                    title="操作"
                    :width="360"
                    fixed="right"
                >
                    <template #cell="{ record }">
                        <a-space>


                            <a-button
                                status="success"
                                type="primary"
                                size="mini"
                                @click="handleShare(record)"
                            >
                                分享
                            </a-button>

                            <a-button
                                status="success"
                                type="primary"
                                size="mini"
                                @click="handleData(record.id)"
                            >
                                数据
                            </a-button>

                            <a-button
                                type="primary"
                                size="mini"
                                @click="handleCopy(record)"
                            >
                                复制
                            </a-button>

                            <a-button
                                type="primary"
                                size="mini"
                                @click="handleConfig(record.id)"
                            >
                                配置
                            </a-button>
                            <a-button
                                type="primary"
                                size="mini"
                                @click="handleEdit(record.id)"
                            >
                                编辑
                            </a-button>
                            <a-button
                                type="primary"
                                status="danger"
                                size="mini"
                                @click="handleDelete(record.id)"
                            >
                                删除
                            </a-button>
                        </a-space>
                    </template>
                </a-table-column>
            </template>
        </a-table>
    </div>

    <a-modal unmount-on-close v-model:visible="isShowConfig" :on-before-ok="saveConfig" ok-text="保存">
        <template #title>
            配置问卷
        </template>
        <div>
            <a-form ref="formRef" :model="form"  auto-label-width>
                <a-form-item field="title" label="标题"
                             :rules="[{required:true,message:'请输入标题'},{minLength:1,maxLength:20,message:'标题最大20字符'}]">
                    <a-input v-model="form.title" placeholder="请输入问卷标题" />
                </a-form-item>
                <a-form-item field="description" label="描述">
                    <a-input v-model="form.description" placeholder="" />
                </a-form-item>
                <a-form-item field="isLogin" label="登录校验">
                    <a-switch v-model="form.isLogin" :checked-value="1" :unchecked-value="0" >
                        <template #checked>
                            ON
                        </template>
                        <template #unchecked>
                            OFF
                        </template>
                    </a-switch>
                </a-form-item>
                <a-form-item field="isRepeated" label="允许重复提交">
                    <a-switch v-model="form.isRepeated" :checked-value="1" :unchecked-value="0" >
                        <template #checked>
                            ON
                        </template>
                        <template #unchecked>
                            OFF
                        </template>
                    </a-switch>
                </a-form-item>
                <a-form-item field="status" label="状态">
                    <a-select v-model="form.status" :style="{width:'220px'}">
                        <a-option :value="0">未发布</a-option>
                        <a-option :value="1">发布中</a-option>
                        <a-option :value="2">已关闭</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="生效时间">
                    <a-range-picker
                        style="width: 360px; margin: 0 24px 24px 0;"
                        :model-value="[form.starttime, form.endtime]"
                        show-time
                        format="YYYY-MM-DD HH:mm"
                        @ok="timeOk"
                    />
                </a-form-item>
                <a-form-item field="bgimg" label="背景图片" >
                    <a-image
                        class="rounded-lg"
                        width="180"
                        :src="form.bgimg"
                    />
                    <a-upload
                              class="ml-4" :limit="1"
                              withCredentials
                              name="file"
                              accept="image/*"
                              :on-before-remove="removeUpload"
                              @success="uploadSuccess"
                              :action="BASE_URL + '/files/upload'"/>
                </a-form-item>

                <a-form-item field="cover" label="封面图片" >
                    <a-image
                        class="rounded-lg"
                        width="180"
                        :src="form.cover"
                    />
                    <a-upload
                        class="ml-4" :limit="1"
                        withCredentials
                        name="file"
                        accept="image/*"
                        :on-before-remove="removeCoverUpload"
                        @success="uploadCoverSuccess"
                        :action="BASE_URL + '/files/upload'"/>
                </a-form-item>
            </a-form>

        </div>
    </a-modal>

<!--    分享弹窗-->
    <a-modal v-model:visible="isShowShare">
        <template #title>
            分享问卷
        </template>
        <div>
            <h2 class="text-center text-lg font-bold">{{shareName}}</h2>
<!--            居中-->
            <div class="flex justify-center mb-3">
                <vue-qrcode :value="shareUrl" :width="180"></vue-qrcode>
            </div>
            <h3>分享链接：{{shareUrl}} <icon-copy class="cursor-pointer" @click="copyUrl"/></h3>

            <div class="flex justify-center mt-3">
                <a-button type="primary" @click="goPreview">预览</a-button>
                <a-button class="ml-6" type="primary" status="success" @click="uploadTemplate">上传为模板</a-button>
            </div>
        </div>
    </a-modal>

</template>


<style scoped>

</style>
